package org.example;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;



public class PdfAdRemover {
    private List<String> endKeywords;

    public PdfAdRemover(List<String> endKeywords) {
        this.endKeywords = endKeywords;
    }
    // 添加常量
    private static final String FONT_PATH = "/fonts/SourceHanSansSC-VF.ttf";
    /**
     * 查找包含结束关键词的最后一页
     */
    private int findLastContentPage(PDDocument document) throws IOException {
        PDFTextStripper textStripper = new PDFTextStripper();
        int totalPages = document.getNumberOfPages();
        int lastFoundPage = -1;

        for (int i = 0; i < totalPages; i++) {
            textStripper.setStartPage(i + 1);
            textStripper.setEndPage(i + 1);
            String pageText = textStripper.getText(document);

            // 打印当前页内容
            System.out.println("====== 第 " + (i + 1) + " 页内容 ======");
            System.out.println(pageText);
            System.out.println("===============================");

            // 检查是否包含关键词
            for (String keyword : endKeywords) {
                if (pageText.contains(keyword)) {
                    lastFoundPage = i; // 更新为最后一个包含关键词的页面
                }
            }
        }
        return lastFoundPage;
    }

    /**
     * 移除PDF中的广告内容
     */
    public boolean removeAds(String inputFilePath, String outputFilePath) throws IOException {
        File inputFile = new File(inputFilePath);
        if (!inputFile.exists() || !inputFile.isFile()) {
            throw new IOException("输入文件不存在或不是有效文件: " + inputFilePath);
        }

        try (PDDocument document = PDDocument.load(inputFile)) {
            int totalPages = document.getNumberOfPages();
            System.out.println("PDF总页数: " + totalPages);
            int lastContentPage = findLastContentPage(document);

            if (lastContentPage == -1) {
                System.out.println("未找到任何结束关键词，输出原始PDF");
                document.save(outputFilePath);
                return false;
            }

            System.out.println("找到最后包含结束关键词的页面: " + (lastContentPage + 1));
            boolean contentModified = false;

            // 1. 处理包含结束关键词的页面（删除后续内容）
            PDPage targetPage = document.getPage(lastContentPage);
            PDFTextStripper textStripper = new PDFTextStripper();
            textStripper.setStartPage(lastContentPage + 1);
            textStripper.setEndPage(lastContentPage + 1);
            String pageText = textStripper.getText(document);

            // 找到第一个关键词位置并截断
            int keywordPosition = -1;
            String foundKeyword = null;
            for (String keyword : endKeywords) {
                int pos = pageText.indexOf(keyword);
                if (pos != -1) {
                    keywordPosition = pos;
                    foundKeyword = keyword;
                    break;
                }
            }

            // 修改removeAds方法中的字体加载部分
            // 修改removeAds方法中的文本绘制部分
            if (keywordPosition != -1) {
                String truncatedText = pageText.substring(0, keywordPosition + foundKeyword.length());
                
                // 使用项目资源目录下的字体文件
                try (InputStream fontStream = getClass().getResourceAsStream(FONT_PATH);
                     PDPageContentStream contentStream = new PDPageContentStream(document, targetPage, 
                         PDPageContentStream.AppendMode.OVERWRITE, true)) {
                    
                    PDType0Font font = PDType0Font.load(document, fontStream);
                    float fontSize = 12;
                    
                    // 获取页面裁剪区域，计算文本可用宽度
                    PDRectangle cropBox = targetPage.getCropBox();
                    float leftMargin = cropBox.getLowerLeftX() + 50; // 左边距
                    float rightMargin = cropBox.getUpperRightX() - 50; // 右边距
                    float availableWidth = rightMargin - leftMargin; // 文本可用宽度
                    float lineHeight = -15; // 行高（负值表示向下）
                    
                    contentStream.beginText();
                    contentStream.setFont(font, fontSize);
                    contentStream.newLineAtOffset(leftMargin, cropBox.getUpperRightY() - 50); // 设置起始位置
                    
                    String[] lines = truncatedText.split("\n");
                    for (String line : lines) {
                        if (!line.trim().isEmpty()) {
                            line = line.replaceAll("\\r$", ""); // 删除末尾的\r
                            
                            // 计算当前文本宽度
                            float textWidth = font.getStringWidth(line) * fontSize / 1000;
                            
                            // 如果文本宽度超过可用宽度，则进行换行处理
                            if (textWidth > availableWidth) {
                                List<String> wrappedLines = wrapText(line, font, fontSize, availableWidth);
                                for (String wrappedLine : wrappedLines) {
                                    contentStream.showText(wrappedLine);
                                    contentStream.newLineAtOffset(0, lineHeight);
                                }
                            } else {
                                contentStream.showText(line);
                                contentStream.newLineAtOffset(0, lineHeight);
                            }
                        }
                    }
                    contentStream.endText();
                }
                contentModified = true;
            }

            // 2. 删除结束页之后的所有页面
            int pagesToRemove = totalPages - lastContentPage - 1;
            if (pagesToRemove > 0) {
                System.out.println("删除广告页面: " + pagesToRemove + " 页");
                for (int i = totalPages - 1; i > lastContentPage; i--) {
                    document.removePage(i);
                }
                contentModified = true;
            }

            document.save(outputFilePath);
            System.out.println("处理完成，输出文件: " + outputFilePath);
            return contentModified;
        }
    }

    // 添加文本换行辅助方法
    private List<String> wrapText(String text, PDType0Font font, float fontSize, float maxWidth) throws IOException {
        List<String> wrappedLines = new ArrayList<>();
        StringBuilder currentLine = new StringBuilder();
        String[] words = text.split("(?<=\\s)"); // 按空格拆分，保留空格
    
        for (String word : words) {
            float wordWidth = font.getStringWidth(currentLine + word) * fontSize / 1000;
            if (wordWidth <= maxWidth) {
                currentLine.append(word);
            } else {
                if (currentLine.length() > 0) {
                    wrappedLines.add(currentLine.toString());
                    currentLine = new StringBuilder(word);
                } else {
                    // 单个单词超过最大宽度，强制拆分
                    float charWidth = font.getStringWidth(word.substring(0, 1)) * fontSize / 1000;
                    int maxChars = (int)(maxWidth / charWidth);
                    for (int i = 0; i < word.length(); i += maxChars) {
                        int end = Math.min(i + maxChars, word.length());
                        wrappedLines.add(word.substring(i, end));
                    }
                    currentLine.setLength(0);
                }
            }
        }
    
        if (currentLine.length() > 0) {
            wrappedLines.add(currentLine.toString());
        }
    
        return wrappedLines;
    }
}